const app = getApp();
const api = require('../../utils/api');

var animation = {};

//初始化预约时间可选范围
let now = new Date(); //现在时间
let year = now.getFullYear();
let month = now.getMonth() + 1;
let day = now.getDate();
let startDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day); //格式化日期

Page({
    data: {
        status: '', //订单状态
        afterSalesStatus: '', //退货状态
        statusList: [
            {id: 0, status: '', afterSalesStatus: '', title: '全部'},
            {id: 1, status: 1, afterSalesStatus: 0, title: '待支付'},
            {id: 2, status: 2, afterSalesStatus: 0, title: '待核销'},
            {id: 3, status: 4, afterSalesStatus: 0, title: '已完成'},
            {id: 4, status: 3, afterSalesStatus: 0, title: '已取消'},
            {id: 5, status: '', afterSalesStatus: 4, title: '已退款'},
        ],

        //搜索订单字段
        orderNo: '',
        beginTime: '',
        endTime: '',
        orderStatus: '',
        orderStatusText: '',
        slideAnimation: '', //下拉弹窗动画

        orderList: [], //订单列表
        pageNum: 1,
        pageSize: 10,
        total: 0,
        noContent: false, //无数据
        isFinished: false, //加载结束

        currentItem: '',
        currentIndex: 0,
        showEditBookTime: false,
        editBookTimeRemark: '', //修改备注
        newBookDate: '', //预约日期
        newBookTime: '', //预约时间
        startDate: startDate,

        showRefund: false, // 退款弹窗
        refundReasonList: ['顾客不想要了', '拍错/多拍/重复下单', '商品信息描述不符', '商品损坏/有污渍', '商品漏发/少发', '发错货/款式/型号/尺寸不对', '效果与预期不符', '其他'],
        refundReason: '', //退款原因
        refundReasonText: '', //退款原因文字
        refundReasonOther: '', //退款其他原因
    },
    onLoad(options) {
        this.getData();
    },
    onShow() {
        animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease-out',
        });
    },
    
    getData() { //获取列表数据
        let params = {
            clientUserType: 1, //客户端用户类型：0消费者、1商家
            orderStatus: this.data.status, //订单状态：1.待付款 2.已付款 3.已取消
            afterSalesStatus: this.data.afterSalesStatus,
            orderNo: this.data.orderNo,
            beginTime: this.data.beginTime ? this.data.beginTime + ' 00:00:00' : '',
            endTime: this.data.endTime ? this.data.endTime + ' 23:59:59' : '',
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post('/merchant/order/page', params)
            .then(res => {
                let list = res.content;
                //整理数据
                list.forEach(item => {
                    //日期格式化
                    item.createTime = app.filterDate(item.createTime);
                    //价格格式化
                    item.payableAmount = item.payableAmount.toFixed(2);
                    //计算消费券总数
                    let couponAmount = 0;
                    item.skuList.forEach(pro => {
                        couponAmount = couponAmount + (pro.memberCoupon * pro.quantity);
                        pro.price = pro.price.toFixed(2);
                        pro.memberPrice = pro.memberPrice.toFixed(2);
                    });
                    item.couponAmount = couponAmount;
                });
                let newList = [...this.data.orderList, ...list];

                this.setData({
                    orderList: newList,
                    total: res.total
                });

                //是否无内容标识
                if(this.data.orderList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.orderList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
                wx.stopPullDownRefresh();
            })
    },

    // 订单搜索
    toggleSearch() { //点击搜索订单弹窗
        if(this.data.showSearch) {
            this.closeSearch();
        } else {
            this.openSearch();
        }
    },
    openSearch() { //打开搜索订单下拉弹窗
        animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease-out',
        });
        // animation.top('88rpx').step();
        animation.top('0').step();

        this.setData({
            showSearch: true,
            slideAnimation: animation.export(),
        });
    },
    closeSearch() { //关闭搜索订单下拉弹窗
        animation.top('-100%').step();

        this.setData({
            showSearch: false,
            slideAnimation: animation.export(),
        });
    },
    bindinput(e) { //输入框监听
        let item = e.currentTarget.dataset.item;
        let val = e.detail.value;
        
        this.setData({
            [item]: val
        });
    },
    bindStatusChoose(e) { //选择订单状态
        this.setData({
            orderStatus: this.data.statusList[e.detail.value].id,
            orderStatusText: this.data.statusList[e.detail.value].title,
            status: this.data.statusList[e.detail.value].status, //订单状态
            afterSalesStatus: this.data.statusList[e.detail.value].afterSalesStatus, //退货状态
        });
    },
    bindDateChoose(e) { //选择日期
        let item = e.currentTarget.dataset.item;
        this.setData({
            [item]: e.detail.value,
        });
    },
    submitSearch() { //提交搜索
        if(this.data.beginTime && !this.data.endTime) {
            wx.showToast({
                title: '请选择搜索结束日期！',
                icon: 'none'
            });
            return;
        }
        if(!this.data.beginTime && this.data.endTime) {
            wx.showToast({
                title: '请选择搜索开始日期！',
                icon: 'none'
            });
            return;
        }
        if(this.data.beginTime && this.data.endTime) {
            let beginTime = new Date(this.data.beginTime);
            let endTime = new Date(this.data.endTime);
            if(beginTime > endTime) {
                wx.showToast({
                    title: '开始日期不能大于结束日期！',
                    icon: 'none'
                });
                return;
            }
        }

        this.setData({
            orderList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.getData();
        this.closeSearch();
    },
    resetSearch() { //重置搜索
        this.setData({
            orderNo: '',
            status: '', //订单状态
            afterSalesStatus: '', //退货状态
            beginTime: '',
            endTime: '',
            orderStatus: '',
            orderStatusText: '',
            orderList: [],
            pageNum: 1,
            total: 0,
            noContent: false,
            isFinished: false,
        });

        this.getData();
        this.closeSearch();
    },

    //订单操作
    viewDetail(e) { //查看详情
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/orderDetail/orderDetail?id=${id}&type=1`,
        });
    },
    gotoPay(e) { //去付款（代购订单）
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/orderPay/orderPay?id=${id}&dir=1`,
        });
    },

    editBookTime(e) { //修改预约时间
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        let bookDate = '';
        let bookTime = '';
        if(item.planPickupTime) {
            bookDate = item.planPickupTime.split(' ')[0];
            let time = item.planPickupTime.split(' ')[1];
            bookTime = time.split(':')[0] + ':' + time.split(':')[1];
        }
        this.setData({
            newBookDate: bookDate,
            newBookTime: bookTime,
            currentItem: item,
            currentIndex: index,
            showEditBookTime: true
        });
    },
    closeEditBookTime() { //关闭预约时间
        this.setData({
            showEditBookTime: false,
            newBookDate: '',
            newBookTime: '',
            editBookTimeRemark: '',
        });
    },
    submitEditBookTime() {
        if(!this.data.newBookDate) {
            wx.showToast({
                title: '请选择预约日期！',
                icon: 'none'
            });
            return;
        }
        if(!this.data.newBookTime) {
            wx.showToast({
                title: '请选择预约时间！',
                icon: 'none'
            });
            return;
        }
        if(!this.data.editBookTimeRemark) {
            wx.showToast({
                title: '请输入修改原因！',
                icon: 'none'
            });
            return;
        }
        let params = {
            orderId: this.data.currentItem.id,
            planPickupTime: this.data.newBookDate + ' ' + this.data.newBookTime + ':00',
            changeRemark: this.data.editBookTimeRemark,
        }
        api.post('/merchant/order/plan/time/change', params)
            .then(() => {
                wx.showToast({
                    title: '修改成功！',
                    icon: 'none'
                });

                this.setData({
                    [`orderList[${this.data.currentIndex}].planPickupTime`]: this.data.newBookDate + ' ' + this.data.newBookTime + ':00'
                });
                this.closeEditBookTime();
            })
    },

    refundApply(e) { //提交退款申请（线下收款订单or账户余额支付订单）
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        this.setData({
            currentItem: item,
            currentIndex: index,
            showRefund: true,
        });
    },
    closeRefund() {
        this.setData({
            showRefund: false,
            refundReason: '',
            refundReasonText: '',
            refundReasonOther: '',
        });
    },
    chooseReason(e) { //选择退款原因
        this.setData({
            refundReasonText: this.data.refundReasonList[e.detail.value],
        });
    },
    submitRefund() {
        if(!this.data.refundReasonText) {
            wx.showToast({
                title: '请选择退款原因！',
                icon: 'none'
            });
            return;
        }
        if(this.data.refundReasonText == '其他' && !this.data.refundReasonOther) {
            wx.showToast({
                title: '请填写退款原因！',
                icon: 'none'
            });
            return;
        }

        let refundReason = this.data.refundReasonText == '其他' ? '其他：' + this.data.refundReasonOther : this.data.refundReasonText;
        let url = this.data.currentItem.orderType == 5 ? `/payment/ccb/refund?orderNo=${this.data.currentItem.orderNo}&refundReason=${refundReason}` : `/payment/account/refund?orderNo=${this.data.currentItem.orderNo}&refundReason=${refundReason}`;

        api.post(url)
            .then(() => {
                wx.showToast({
                    title: '退款提交成功！',
                    icon: 'success'
                });

                this.setData({
                    [`orderList[${this.data.currentIndex}].afterSalesStatus`]: 4,
                });
                this.closeRefund();
            })
    },

    onPullDownRefresh() {
        //下拉刷新
        this.setData({
            orderList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.getData();
    },
    onReachBottom() {
        //加载更多
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
            });
            
            setTimeout(() => {
                this.getData();
            }, 800);
        }
    },
})